package cn.wen.eeayjoke.config;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;

import java.util.Map;
import java.util.TreeMap;

import cn.wen.base.base.ActivityManager;
import cn.wen.base.util.AppConfig;

/**
 * URL封装对象
 */
public class URLS {

    private static final String NAME = "URLS";
    /**
     * 缓存的URL
     */
    private static final String KEY_URL = "KEY_URL";
    /**
     * 描述
     */
    private static final String DESC = "DESC";
    private static Map<Integer, URLS> map = new TreeMap<>();

    static {

        map.put(0, new URLS("http://mapi.car-house.cn/", "正式"));
        map.put(1, new URLS("http://dev.car-house.cn/", "测试dev"));
        map.put(2, new URLS("http://preapi.car-house.cn/", "预正式"));
        map.put(3, new URLS("http://carhouse.imwork.net:8888/", "测试imwork"));
        // 添加一个缓存的
        String url = getSaveUrl();
        if (!TextUtils.isEmpty(url)) {
            map.put(4, new URLS(url, getSaveDesc()));
        }
    }

    private String mBaseUrl;
    private String mDesc;

    public URLS(String baseUrl, String desc) {
        this.mBaseUrl = baseUrl;
        this.mDesc = desc;
    }

    public String getBaseUrl() {
        return mBaseUrl;
    }

    public String getDesc() {
        return mDesc;
    }

    /**
     * 根据位置获取URL对象
     */
    public static URLS getURLS(int position) {
        return map.get(position);
    }

    public static Map<Integer, URLS> getURLS() {
        return map;
    }

    /**
     * 调试切换IP用
     */
    public static void saveUrl(String url, String desc) {
        // 如果是调试，就缓存起来
        if (AppConfig.IS_DEBUG) {
            SharedPreferences sp = AppConfig.getInstance().getContext()
                    .getSharedPreferences(NAME, Context.MODE_PRIVATE);
            sp.edit()
                    .putString(KEY_URL, url)
                    .putString(DESC, desc)
                    .commit();
            map.put(4, new URLS(url, desc));
            ActivityManager.getInstance().exit();
            // 杀死自己的进程
            android.os.Process.killProcess(android.os.Process.myPid());
        }
    }

    public static String getSaveUrl() {
        SharedPreferences sp = AppConfig.getInstance().getContext()
                .getSharedPreferences(NAME, Context.MODE_PRIVATE);
        String url = sp.getString(KEY_URL, "");
        return url;
    }

    private static String getSaveDesc() {
        SharedPreferences sp = AppConfig.getInstance().getContext()
                .getSharedPreferences(NAME, Context.MODE_PRIVATE);
        String desc = sp.getString(DESC, "");
        return desc;
    }
}
